package com.spider.admin.init;


import com.spider.admin.conf.ENVConf;
import com.spider.admin.utils.OSCommandUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Component
public class UiServer {
    @Autowired
    private ENVConf envConf;

    public void startUiServer() {
        try {
            if (OSCommandUtil.hasRunPort(envConf.getUiRunPort())) {
                throw new Exception("Web容器端口(" + envConf.getUiRunPort() + ")已经占用");
            }
            String[] excFileInfos = findUiContainerExeFile();
            OSCommandUtil.executeCmd(excFileInfos[0], " start " + excFileInfos[1], false, false);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage() + "----Web容器启动失败");
        }
    }

    public void stopUiServer() {
        try {
            if (OSCommandUtil.hasRunPort(envConf.getUiRunPort())) {
                String[] excFileInfos = findUiContainerExeFile();
                OSCommandUtil.executeCmd(excFileInfos[0], excFileInfos[1] + " -s stop ", true, false);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage() + "----Web容器关闭异常");
        }
    }

    private String[] findUiContainerExeFile() {
        String[] strs = new String[2];
        strs[0] = envConf.getUiContainerBasePath();
        ;
        if (OSCommandUtil.isWinOS()) {
            strs[1] = "nginx.exe";
        } else {
            strs[0] = strs[0] + "\\bin";
            strs[1] = "openrestry";
        }
        Path filePath = Paths.get(strs[0], strs[1]);
        boolean bol = Files.exists(filePath);
        if (bol) {
            return strs;
        } else {
            return null;
        }
    }
}
